package cn.jbt.api.admin.filter;


import cn.dev33.satoken.stp.StpUtil;
import cn.jbt.api.admin.entity.SysUser;
import cn.jbt.api.admin.entity.vo.LoginInfoVO;
import cn.jbt.api.admin.repository.SysUserRepository;
import cn.jbt.common.util.ApplicationContextUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.http.HttpStatus;

import java.io.IOException;

@Slf4j
public class TokenFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletResponse httpServletResponse = (HttpServletResponse) servletResponse;

        if (StpUtil.isLogin()) {
            ApplicationContext context = ApplicationContextUtil.getContext();
            SysUserRepository sysUserRepository = context.getBean(SysUserRepository.class);

            SysUser sysUser = sysUserRepository.findFirstById(StpUtil.getLoginIdAsLong());
            if (null == sysUser || !sysUser.getStatus().equals(1)) {
                httpServletResponse.setStatus(HttpStatus.UNAUTHORIZED.value());
                return;
            }

            LoginInfoVO loginInfoVO = new LoginInfoVO();
            loginInfoVO.setId(sysUser.getId());
            loginInfoVO.setUsername(sysUser.getUsername());
            loginInfoVO.setMobile(sysUser.getMobile());
            loginInfoVO.setNickname(sysUser.getNickname());
            loginInfoVO.setRoot(sysUser.getRoot());

            // 设置当前请求上下文, 把用户信息填充进去
            LoginInfoAccessContext.setLoginInfo(loginInfoVO);
        }

        filterChain.doFilter(servletRequest, servletResponse);
    }
}
